/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.web.action;

import com.wii.elpro.dao.hb.ProdukDAOImpl;
import com.wii.elpro.entity.InqueryItem;
import com.wii.elpro.entity.User;
import com.wii.elpro.web.form.InquiryAddItemForm;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author hp02
 */
public class InquirySetItemAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User user = (User)sess.getAttribute("userSession");       
        if(user==null){
            return mapping.findForward("gagalLogin");            
        }  
        ActionForward af = null;
        InquiryAddItemForm f = (InquiryAddItemForm) form;
        InqueryItem item = new InqueryItem();
        item.setProduk(new ProdukDAOImpl().getProduk(f.getProduk()));
        item.setJumlah(f.getJumlah());
        ActionMessages messages = new ActionMessages();
        
        String id;
        if(sess.getAttribute("idInquiry")!=null) {
            id = (String) sess.getAttribute("idInquiry");
        } else {
            id = 0+"";
        }
        try {
            List<InqueryItem> listItem = new ArrayList<InqueryItem>();  
            if(sess.getAttribute("listItem")!=null) {
                listItem = (List<InqueryItem>) sess.getAttribute("listItem");
            }
            listItem.add(item);
            sess.setAttribute("listItem", listItem);        
            messages.add("customMessage", new ActionMessage("customMessage", "Material is successfully added to product."));
            saveMessages(sess, messages);
            af = new ActionForward(mapping.findForward("success").getPath()+"?id="+id, true);
        } catch (Exception ex) {
            messages.add("message", new ActionMessage("customMessage", "Application is fail to add material to product. Please contact my developer."));
            saveMessages(sess, messages);
            ex.printStackTrace();
            af = new ActionForward(mapping.findForward("fail"));
        }
        return af;
    }
}
